/*
 * @Description: ------------ fileDescription -----------
 * @Author: snows_l snows_l@163.com
 * @Date: 2024-08-13 19:33:14
 * @LastEditors: snows_l snows_l@163.com
 * @LastEditTime: 2025-01-09 12:23:11
 * @FilePath: \Backstage\Server\src\router\comment.js
 */
const createSql = require('../utils/sql');
const express = require('express');
const db = require('../utils/connDB');
const router = express.Router();
const IP2Region = require('ip2region').default;
const { getOS, getBrowserName, getCityByIp, handleError } = require('../utils/common');
const { verifyToken } = require('../utils/handleToken');
const moment = require('moment');
const { sendEmail } = require('../utils/email');

// 获取后台  留言评论列表
router.get('/list', (req, res) => {
  let { page = 1, size = 5, comment, type, isAll = false, isCheck = 0 } = req.query;
  let offset = (page - 1) * size;
  let sql =
    'select* from comment where 1=1' +
    (isCheck == 0 ? '' : ` and isCheck = ${isCheck}`) +
    (isAll ? '' : ` and isPrivacy = 0`) +
    (type == 1 ? ` and type = 1` : ` and type = 0`) +
    (comment ? ` and comment like '%${comment}%'` : '') +
    ` and pId = '0' order by time desc limit ${size} offset ${offset}`;
  let lenSql =
    'select count(*) as total from comment where 1=1' +
    (isCheck == 0 ? '' : ` and isCheck = ${isCheck}`) +
    (isAll ? '' : ` and isPrivacy = 0`) +
    (type == 1 ? ` and type = 1` : ` and type = 0`) +
    (comment ? ` and comment like '%${comment}%'` : '') +
    " and pId = '0'";
  try {
    db.queryAsync(sql)
      .then(result => {
        db.queryAsync(lenSql)
          .then(lenResult => {
            let str = '';
            result.results
              .map(item => item.id)
              .forEach(item => {
                str += "'" + item + "',";
              });
            str = str.substring(0, str.length - 1);
            let sql2 = `select* from comment where 1=1 ${isCheck == 0 ? '' : ` and isCheck = ${isCheck}`} ${isAll ? '' : ` and isPrivacy = 0`}  and pId in (${str})`;
            db.queryAsync(sql2)
              .then(result2 => {
                console.log('-------result.results  -------', result.results);
                let data = [...result.results, ...result2.results];
                res.send({
                  code: 200,
                  data: data,
                  msg: 'success',
                  total: lenResult.results[0].total
                });
              })
              .catch(err => {
                handleError(res, err);
              });
          })
          .catch(err => {
            handleError(res, err);
          });
      })
      .catch(err => {
        handleError(res, err);
      });
  } catch (error) {
    res.send({
      code: 200,
      data: [],
      msg: '500 error=' + error,
      total: 0
    });
  }
});

// 获取弹幕列表
router.get('/danmu', (req, res) => {
  let sql = `select id, qq, comment, likeCount  from comment where 1=1 and isCheck = 1 and type = 0 order by time desc`;
  try {
    db.queryAsync(sql).then(result => {
      res.send({
        code: 200,
        data: result.results,
        msg: 'success'
      });
    });
  } catch (error) {
    res.send({
      code: 200,
      data: [],
      msg: '500 error=' + error,
      total: 0
    });
  }
});

// 获取评论列表  blog
router.get('/list2', (req, res) => {
  let { articleId, isCheck = 0, page = 1, size = 10 } = req.query;
  let offset = (page - 1) * size;
  let sql =
    'select* from comment where 1=1 and type = 1 and isPrivacy = 0 ' +
    (isCheck == 0 ? '' : ` and isCheck = ${isCheck}`) +
    (articleId ? ` and articleId = ${articleId}` : '') +
    ` and pId = '0' order by time asc limit ${size} offset ${offset}`;

  let lenSql =
    'select count(*) as total from comment where 1=1 and type = 1 and isPrivacy = 0 ' +
    (isCheck == 0 ? '' : ` and isCheck = ${isCheck}`) +
    (articleId ? ` and articleId = ${articleId}` : '') +
    " and pId = '0'";
  try {
    db.queryAsync(sql).then(result => {
      db.queryAsync(lenSql).then(lenResult => {
        let str = '';
        result.results
          .map(item => item.id)
          .forEach(item => {
            str += "'" + item + "',";
          });
        str = str.substring(0, str.length - 1);
        let sql2 = `select* from comment where 1=1 and type = 1 and articleId = ${articleId} and isPrivacy = 0 ${isCheck == 0 ? '' : ` and isCheck = ${isCheck}`} ${
          str != '' ? ` and pId in (${str})` : ''
        }`;
        db.queryAsync(sql2).then(result2 => {
          let data = [...result.results, ...result2.results];
          res.send({
            code: 200,
            data: data,
            msg: 'success',
            total: lenResult.results[0].total
          });
        });
      });
    });
  } catch (error) {
    res.send({
      code: 200,
      data: [],
      msg: '500 error=' + error,
      total: 0
    });
  }
});

// 新增评论
router.post('/add', async (req, res) => {
  let { qq, nickName, comment, avatarUrl, email, websiteUrl, isPrivacy, isEmailFeekback, type = 0, pId = 0, toNickName, articleId, toId = 0 } = req.body;
  isPrivacy = isPrivacy * 1;
  isEmailFeekback = isEmailFeekback * 1;
  const os = getOS(req.headers['user-agent']);
  const browser = getBrowserName(req.headers['user-agent']);
  let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || 'Unknown';
  if (ip.includes(':')) {
    ip = ip.includes(':') ? ip.split(':').slice(-1)[0] : ip;
  }
  let { address } = await getCityByIp(ip);
  let id = (type == 1 ? 'PL' : 'LY') + moment().format('YYYYMMDDHHmmss');

  let sql = createSql
    .insert('comment')
    .set({
      id,
      qq,
      nickName,
      comment,
      avatarUrl,
      email,
      websiteUrl,
      isPrivacy,
      isEmailFeekback,
      os,
      browser,
      type,
      pId,
      toId,
      toNickName,
      articleId,
      city: address,
      ip,
      time: moment().format('YYYY-MM-DD HH:mm:ss'),
      isCheck: 0
    })
    .end();
  try {
    db.queryAsync(sql).then(result => {
      res.send({
        code: 200,
        data: null,
        msg: 'success'
      });
      // 评论
      if (type == 1) {
        if (toId != 0 && toId != '') {
          let sql2 = 'select* from comment where 1=1 and id =' + `'${toId}'`;
          db.queryAsync(sql2).then(result2 => {
            // 回复并且允许邮件通知
            if (result2.results[0].isEmailFeekback == 1) {
              let toEmail = result2.results[0].email ? result2.results[0].email : result2.results[0].qq + '@qq.com';
              // 回复并且允许邮件通知
              const params = {
                to: toEmail,
                path: '/article/detail?id=' + articleId,
                comment: comment,
                username: nickName,
                isBack: true,
                isComment: true
              };
              sendEmail(params);
            }
          });
        } else {
          // 有人评论 通知博主
          const params = {
            to: 'snows_l@163.com',
            path: '/article/detail?id=' + articleId,
            comment: comment,
            username: nickName,
            isBack: false,
            isComment: true
          };
          sendEmail(params);
        }
      } else {
        if (toId != 0 && toId != '') {
          let sql2 = 'select* from comment where 1=1 and id =' + `'${toId}'`;
          db.queryAsync(sql2).then(result2 => {
            // 回复并且允许邮件通知
            if (result2.results[0].isEmailFeekback == 1) {
              let toEmail = result2.results[0].email ? result2.results[0].email : result2.results[0].qq + '@qq.com';
              // 回复并且允许邮件通知
              const params = {
                to: toEmail,
                path: '/msg-board',
                comment: comment,
                username: nickName,
                isBack: true,
                isComment: false
              };
              sendEmail(params);
            }
          });
        } else {
          // 留言
          const params = {
            to: 'snows_l@163.com',
            path: '/msg-board',
            comment: comment,
            username: nickName,
            isBack: false,
            isComment: false
          };
          sendEmail(params);
        }
      }
    });
  } catch (error) {
    res.send({
      code: 500,
      data: null,
      msg: '500 error=' + error
    });
  }
});

// 编辑留言
router.put('/edit', (req, res) => {
  let token = req.cookies['bs-cookie'];
  try {
    const user = verifyToken(token);
    if (!user) throw new Error('JsonWebTokenError:token验证失败');
    if (user.role_key !== 'admin') throw new Error('ROLE_ERROR:权限不足');
    let { id, qq, nickName, comment, avatarUrl, email, websiteUrl, isPrivacy, isEmailFeekback } = req.body;
    isPrivacy = isPrivacy * 1;
    isEmailFeekback = isEmailFeekback * 1;
    let sql = createSql
      .update('comment')
      .set({ qq, nickName, comment, avatarUrl, email, websiteUrl, isPrivacy, isEmailFeekback })
      .where('id=' + `'${id}'`)
      .end();
    db.queryAsync(sql)
      .then(result => {
        res.send({
          code: 200,
          data: null,
          msg: 'success'
        });
      })
      .catch(err => {
        handleError(res, err);
      });
  } catch (error) {
    handleError(res, error);
  }
});

// 删除留言
router.delete('/del/:id', (req, res) => {
  let token = req.cookies['bs-cookie'];
  try {
    const user = verifyToken(token);
    if (!user) throw new Error('JsonWebTokenError:token验证失败');
    if (user.role_key !== 'admin') throw new Error('ROLE_ERROR:权限不足');
    let { id } = req.params;
    let sql = `DELETE FROM comment WHERE id='${id}'`;
    db.queryAsync(sql)
      .then(result => {
        res.send({
          code: 200,
          data: null,
          msg: 'success'
        });
      })
      .catch(err => {
        handleError(res, err);
      });
  } catch (error) {
    handleError(res, error);
  }
});

// 点赞
router.post('/like', (req, res) => {
  let { id } = req.body;
  let sql = `UPDATE comment SET likeCount = likeCount + 1 WHERE id='${id}'`;
  try {
    db.queryAsync(sql).then(result => {
      let likeCountSql = `SELECT likeCount, email FROM comment WHERE id='${id}'`;
      db.queryAsync(likeCountSql).then(result2 => {
        let likeCount = result2.results[0].likeCount;
        // let params = {
        //   to: result2.results[0].email,
        //   path: '/msg-board',
        //   comment: '你的留言被点赞了',
        //   username: '系统',
        //   isBack: false,
        //   isComment: false,
        //   likeCount: likeCount
        // };
        // sendEmail(params);
        res.send({
          code: 200,
          data: likeCount,
          msg: 'success'
        });
      });
    });
  } catch (error) {
    handleError(res, error);
  }
});

// 审核留言
router.post('/audit', (req, res) => {
  let { id } = req.body;
  let sql = `UPDATE comment SET isCheck = 1 WHERE id='${id}'`;
  try {
    db.queryAsync(sql).then(result => {
      res.send({
        code: 200,
        data: null,
        msg: 'success'
      });
    });
  } catch (error) {
    handleError(res, error);
  }
});
module.exports = router;
